package com.example.rentingapp.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.rentingapp.R;
import com.example.rentingapp.enetity.HouseEntity;

import java.util.List;

public class HouseAdapter extends BaseAdapter {
    private List<HouseEntity> mData;
    private Context mContext;

    public HouseAdapter(List<HouseEntity> mData, Context mContext) {
        this.mData = mData;
        this.mContext = mContext;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_item_layout, parent, false);
            holder = new ViewHolder();
            holder.img_house = (ImageView) convertView.findViewById(R.id.img_house);
            holder.tv_rent = (TextView) convertView.findViewById(R.id.tv_rent);
            holder.tv_address = (TextView) convertView.findViewById(R.id.tv_address);
            holder.tv_home_type = (TextView) convertView.findViewById(R.id.tv_home_type);
            holder.tv_time_type = (TextView) convertView.findViewById(R.id.tv_time_type);
            convertView.setTag(holder);//将Holder存储到convertView中
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Bitmap bitmap = null;
        try {
            byte[] bytes = (mData.get(position).getHouse_images()).getBytes("UTF-8");
            byte[] bitmapArray = Base64.decode(bytes, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        holder.img_house.setImageBitmap(bitmap);
        holder.tv_address.setText(mData.get(position).getAddress());
        holder.tv_home_type.setText(mData.get(position).getHome_type());
        holder.tv_time_type.setText(mData.get(position).getTime_type());
        holder.tv_rent.setText(String.valueOf(mData.get(position).getHouse_rent()));

        return convertView;
    }

    static class ViewHolder {
        ImageView img_house;
        TextView tv_rent;
        TextView tv_address;
        TextView tv_home_type;
        TextView tv_time_type;
    }
}
